<!-- 百度地图 -->
<template>
  <div class="map-wrapper">
    <baidu-map class="bm-view" :mapClick="false" :center="center" @zoomend="syncCenterAndZoom" :scroll-wheel-zoom="true" @ready="handler" @mousemove="syncPolyline" @moveend="syncCenterAndZoom_" :zoom="zoom">
      <bm-boundary v-if="showBoundary" :name="zoneBoundary" :strokeWeight="2" strokeColor="blue" fillColor="skyblue" :fillOpacity="0.4"></bm-boundary>
      <!-- 自定义覆盖物 气泡 -->
      <!-- <div v-if="showZone&&zoneGeoPoints.length!=0">
        <zone-overlay v-for="(item, index) in zoneGeoPoints" :key="index" :position="{lng: item.centroid[0], lat:item.centroid[1]}" @click.native="selZone(item, index)" @mouseover.native="selectZone(item, index)" @mouseleave.native="cancelZone" :text="item">
        </zone-overlay>
      </div> -->
      <!-- 自定义覆盖物 长方形 -->
      <!-- <div v-if="showZone===false">
        <around-overlay v-for="(item, index) in aroundGeoPoints" :key="index" @panelClick="aroundClick" :position="{lng: item.lng, lat: item.lat}" :text="item">
        </around-overlay>
      </div> -->
      <!-- marker点位 -->
      <div v-if="!showZone">
        <bm-marker v-if="markerShow" ref="marker" :icon="{url: require('../../assets/marker.png'), size: {width: 32, height: 38}}" v-for="(item,index) in markers" :key="index" @mouseover="infoWindowOpen(item)" @mouseout="infoWindowClose(item)" :position="{lng: item[0], lat:item[1]}">
          <bm-info-window :width="420" :height="0" :position="{lng: item[0], lat:item[1]}" :show="item.show">
            <el-image style="heigth:100px;width:139px;float:left" :src="baseURL+url" fit="fill"></el-image>
            <div class="detail" style="margin-left:150px;">
              <h4>{{pointInfo.address}}</h4>
              <p>资产状态:{{pointInfo.state}}</p>
              <p>住房面积:{{pointInfo.buildArea}}</p>
              <p>租金:{{pointInfo.hire}}</p>
            </div>
          </bm-info-window>
        </bm-marker>
      </div>
      <!-- 自定义地图按钮 -->
      <bm-control style="margin:10px;">
        <!-- <el-button @click="drawer=true" icon="el-icon-search" circle></el-button> -->
        <el-button @click="drawer=true" icon="el-icon-search">资产查询</el-button>
        <el-button v-if="markerShow&&!showZone" @click="toggle('polyline')"><i class="el-icon-edit"></i>{{ polyline.editing ? '退出画笔找房' : '画笔找房' }}</el-button>
      </bm-control>
      <!-- 折线 -->
      <bm-polyline v-if="!paintDown" :path="polyline.paths" @lineupdate="updatePolylinePath"></bm-polyline>
      <!-- 多边形 -->
      <bm-polygon v-if="paintDown" ref="polygon" :path="polyline.paths" />
    </baidu-map>
    <!-- <dataToast v-if="this.$store.state.showAround > ZOOMBOUNDARY ">视野内共有{{aroundCnt}}个房源，拖动地图查看更多～</dataToast> -->
    <dataToast>当前共有{{totals}}处资产</dataToast>
    <!-- 抽屉页面 -->
    <el-drawer title="区域资产" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
      <panel-list :searchData="searchData" @getCheckList="getcheckList" :zoomId="zoomId" />
    </el-drawer>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { BmlMarkerClusterer } from "vue-baidu-map";
import ZoneOverlay from "./components/ZoneOverlay";
import AroundOverlay from "./components/AroundOverlay";
import DataToast from "./components/DataToast";
import RightPanel from "@/components/RightPanel";
import Settings from "../../layout/components/Settings";
import PanelList from "./components/PanelList";
import mapConfig from "@/assets/custom_map_config.json";
import { BmlHeatmap } from "vue-baidu-map";
import {
  getPosition,
  getAll,
  getAllRoom,
  getRoomList,
  getRoomByPoint
} from "@/api/map";
const ZOOMBOUNDARY = 15;
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    BmlMarkerClusterer,
    ZoneOverlay,
    AroundOverlay,
    RightPanel,
    Settings,
    BmlHeatmap,
    PanelList,
    DataToast
  },
  data() {
    //这里存放数据
    return {
      center: { lng: 105.4325634, lat: 28.927475 }, //中心点
      showZone: false, //区域气泡
      showBoundary: false, //行政区域
      zoneBoundary: "泸州市江阳区", //行政区划名称
      zoom: 12, //缩放级别
      show: false,
      markerShow: true, //点位显示
      drawer: false, //抽屉层显示
      map: null,
      direction: "ltr",
      pointInPolygonArray: [],
      zoomId: "",
      polyline: {
        editing: false,
        paths: []
      },
      searchData: {},
      zoneGeoPoints: [], //气泡数组
      aroundGeoPoints: [], //长方体数组
      pointInfo: {},
      markers: [
        //点位数组
        { lng: 105.42049, lat: 28.920773, show: false },
        { lng: 105.43049, lat: 28.930773, show: false },
        { lng: 105.44049, lat: 28.940773, show: false },
        { lng: 105.432276, lat: 28.923555, show: false },
        { lng: 105.433138, lat: 28.929245, show: false },
        { lng: 105.438887, lat: 28.916599, show: false }
      ],
      markers2: [],
      value: [],
      isMouseDown: false, //鼠标按下
      paintStart: false, //开始绘画
      paintDown: false, //绘画完成
      page: 1,
      totals: 0,
      zoneId: null, //点击气泡的id,
      baseURL: "",
      url: "",
      mapStyle: {
        styleJson: mapConfig
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    markerOver(e) {
      console.log("eee", e);
    },
    handler({ BMap, map }) {
      getPosition().then(res => {
        console.log("位置", res);
        this.center = { lng: res.lng, lat: res.lat };
      });
      getAll().then(res => {
        console.log("zone", res);
        this.zoneGeoPoints = res;
        let data = { zoom: this.zoom, value: res };
        this.$store.dispatch("settings/setZoomInfo", { data });
      });
      let data = { page: this.page };
      getAllRoom(data).then(res => {
        this.showZone = true;
        this.searchData = res;
        this.totals = res.total;
      });
      console.log("map", map);
      this.map = map;
      map.addEventListener("mousedown", () => {
        if (!this.polyline.editing) {
          //没在画笔编辑状态
          return;
        }
        this.polyline.paths = []; //每次重新点击时清空画线
        this.paintStart = true;
        this.paintDown = false;
      });
      map.addEventListener("mouseup", e => {
        console.log("鼠标抬起");
        this.paintDown = true;
        this.$nextTick(() => {
          //画笔编辑状态
          if (this.polyline.editing) {
            this.markers = this.caculateEstateContainedInPolygon(
              this.$refs.polygon
            );
            console.log("画完后点位", this.markers);
            this.zoom = 16;
            //抬起时 显示矩形内点位
            this.markerShow = true;
          }
          // this.markers = this.pointInPolygonArray;
        });
      });
    },
    toggle(name) {
      this[name].editing = !this[name].editing;
      this.markerShow = !this.markerShow;
      console.log("是否编辑", this[name].editing);
      if (this[name].editing) {
        this.map.disableDragging();
        this.map.disableScrollWheelZoom();
        this.map.disableDoubleClickZoom();
        this.map.disableKeyboard();
        this.map.setDefaultCursor("crosshair");
      } else {
        this.map.enableDragging();
        this.map.enableScrollWheelZoom();
        this.map.enableDoubleClickZoom();
        this.map.enableKeyboard();
        this.map.setDefaultCursor("default");

        //退出画笔操作 清空矩形点位数组
        this.polyline.paths = [];
        this.zoom = 12;
        this.showZone = true;
        let zoominfo = this.$store.state.settings.zoominfo;
        zoominfo.forEach(element => {
          if (this.zoom === element.data.zoom) {
            this.zoneGeoPoints = element.data.value;
          }
        });
        // zoominfo.forEach(element => {
        //   if (this.zoom === element.data.zoom) {
        //     this.zoneGeoPoints = element.data.value;
        //   }
        // });
      }
    },
    //地图缩放事件
    syncCenterAndZoom(e) {
      if (e.target.getZoom() < this.zoom) {
        this.zoom = e.target.getZoom(); //获取缩放等级
        console.log("缩放等级", this.zoom);
        //当缩放等级小于15时才显示气泡

        this.showZone = true;
        let zoominfo = this.$store.state.settings.zoominfo;
        zoominfo.forEach(element => {
          if (this.zoom === element.data.zoom) {
            this.zoneGeoPoints = element.data.value;
          }
        });
        console.log("vuex里的气泡信息", zoominfo);
      }
    },
    //移动到气泡事件
    selectZone(item, index) {
      this.zoneBoundary = item.boundaryName;
      this.showBoundary = true;
    },
    //离开气泡时事件
    cancelZone() {
      this.showBoundary = false;
    },
    //关闭抽屉
    handleClose(done) {
      done();
    },
    //气泡点击事件
    selZone(item, index) {
      console.log("气泡点击事件", item, index);
      this.zoomId = item.id;
      this.baseURL = process.env.VUE_APP_BASE_API;

      // this.showZone = false;
      // this.$set(this.center, "lng", item.lng);
      // this.$set(this.center, "lat", item.lat);
      // this.zoneBoundary = "";
      // this.showBoundary = false;
      // this.zoom = ZOOMBOUNDARY + 1;
      // updateHouseList 获取周边房源，使用vuex存储部分数据，这里需要自己设计
      // this.updateHouseList(item.lng, item.lat);
      let data = { id: item.id, page: this.page };
      // this.isMarkerShow = item.isPlot;
      // if (item.isPlot) {
      //   console.log("还有气泡");
      //   this.zoom = this.zoom + 1;
      //   this.showZone = true;
      //   getAll(data).then(res => {
      //     console.log("zone", res);
      //     this.zoneGeoPoints = res;
      //     let data = { zoom: this.zoom, value: res };

      //     //把缩放等级和层级气泡存入vuex
      this.$store.dispatch("settings/setZoomInfo", { data });
      //   });
      // } else {
      console.log("没有气泡");
      this.zoom = 15;
      this.center = { lng: item.centroid[0], lat: item.centroid[1] };
      // this.drawer = true;
      this.showZone = false;
      this.markerShow = true;
      this.markers = [];
      getAllRoom(data).then(res => {
        this.markers = res.points;
        this.markers.forEach(item => {
          this.$set(item, "show", false);
        });
        console.log("点击气泡后的点位", this.markers);
        // let markerData = { zoomId: item.id, data: res.points };
        // sessionStorage.setItem("markerInfo", JSON.stringify(markerData));
        this.searchData = res;
        this.totals = res.total;
      });
      // }
    },
    //地图移动结束时触发此事件
    syncCenterAndZoom_(e) {
      console.log("地图移动结束时", e);
      const zoom = e.target.getZoom();
      // if (zoom > ZOOMBOUNDARY) {
      // 更新周边房源数据，仅供参考
      const { lng, lat } = e.target.getCenter();
      console.log("移动后的中心点", lng, lat);
      // this.updateHouseList(lng, lat);
      // }
    },
    //覆盖物的属性发生变化时触发
    updatePolylinePath(e) {
      console.log("覆盖物的属性发生变化时", e);
    },
    //地图移动过程事件
    syncPolyline(e) {
      if (!this.polyline.editing) {
        return;
      }
      if (this.paintStart === true && this.paintDown === false) {
        //如果是画笔编辑状态并且开始画画状态 鼠标是按下状态
        console.log("移动的点", e.point);
        this.polyline.paths.push(e.point);
      }
    },
    //计算地图上点的包含状态
    caculateEstateContainedInPolygon(polygon) {
      // 要注意Point和Circle 都必须是:BMap.Point和BMap.Bounds对象
      this.pointInPolygonArray = [];
      //得到多边形的点数组
      let pointArray = this.polyline.paths;
      //获取多边形的外包矩形
      let bound = polygon.map.getBounds();
      //在多边形内的点的数组
      //计算每个点是否包含在该多边形内
      let markerPoint = [];
      console.log("多边形的外包矩形", bound);
      console.log("多边形的点数组", pointArray);
      // console.log("点位对象", this.markers[0]);
      let polygonMarkers = [];
      console.log("marker点位数组", this.markers);
      this.markers.forEach(i => {
        let point = new BMap.Point(i[0], i[1]);
        let markerPoint = new BMap.Marker(point).point;
        // let markerPoint = this.$refs.marker[i].map.getCenter();
        if (this.isPointInPolygon(markerPoint, bound, pointArray)) {
          this.pointInPolygonArray.push(markerPoint);
          console.log("在多边形里的数组", this.pointInPolygonArray);
          polygonMarkers.push(markerPoint);
        }
      });
      polygonMarkers.forEach(item => {
        item[0] = item.lng;
        item[1] = item.lat;
      });
      return polygonMarkers;
      console.log("在多边形里的数组", this.pointInPolygonArray);
      let estateListAfterDrawing = this.pointInPolygonArray.map(function(item) {
        // return item.getLabel().getContent();
      });
      // return estateListAfterDrawing;
    },
    //判定一个点是否包含在多边形内
    isPointInPolygon(point, bound, pointArray) {
      //首先判断该点是否在外包矩形内，如果不在直接返回false
      if (!bound.containsPoint(point)) {
        return false;
      }
      //如果在外包矩形内则进一步判断
      //该点往右侧发出的射线和矩形边交点的数量,若为奇数则在多边形内，否则在外
      var crossPointNum = 0;
      for (var i = 0; i < pointArray.length; i++) {
        //获取2个相邻的点
        var p1 = pointArray[i];
        var p2 = pointArray[(i + 1) % pointArray.length];
        //如果点相等直接返回true
        if (
          (p1.lng === point.lng && p1.lat === point.lat) ||
          (p2.lng === point.lng && p2.lat === point.lat)
        ) {
          return true;
        }
        //如果point在2个点所在直线的下方则continue
        if (point.lat < Math.min(p1.lat, p2.lat)) {
          continue;
        }
        //如果point在2个点所在直线的上方则continue
        if (point.lat >= Math.max(p1.lat, p2.lat)) {
          continue;
        }
        //有相交情况:2个点一上一下,计算交点
        //特殊情况2个点的横坐标相同
        var crossPointLng;
        if (p1.lng === p2.lng) {
          crossPointLng = p1.lng;
        } else {
          //计算2个点的斜率
          var k = (p2.lat - p1.lat) / (p2.lng - p1.lng);
          //得出水平射线与这2个点形成的直线的交点的横坐标
          crossPointLng = (point.lat - p1.lat) / k + p1.lng;
        }
        //如果crossPointLng的值大于point的横坐标则算交点(因为是右侧相交)
        if (crossPointLng > point.lng) {
          crossPointNum++;
        }
      }
      //如果是奇数个交点则点在多边形内
      return crossPointNum % 2 === 1;
    },
    infoWindowClose(item) {
      item.show = false;
    },
    infoWindowOpen(item) {
      item.show = true;
      let data = { lng: item[0], lat: item[1] };
      getRoomByPoint(data).then(res => {
        this.pointInfo = res.roomInfo;
        this.url = res.url;
      });
    },
    markerClick(item) {
      this.drawer = true;
    },
    aroundClick(item) {
      console.log("around点击", item);
      this.drawer = true;
    },
    getcheckList(list) {
      console.log("地图得到查询的list", list);
      list.rows.forEach(item => {
        this.markers.push([item.lng, item.lat]);
      });
      // this.markers = list.rows;
      this.totals = list.total;
      this.zoom = 15;
      this.showZone = false;
      this.markerShow = true;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.map-wrapper {
  // touch-action: none;
}
.bm-view {
  width: 100%;
  height: calc(100vh - 50px);
  // height: 900px;
}
.block {
  width: 160px;
}
</style>